#include "Font.h"
#include <stdio.h>

int InitFont(Font *font,char *fontname,int w,int h,int cols,int rows,int offset)
{
	FILE *fh=fopen(fontname,"rb");
	if(!fh)
	{
		fprintf(stderr,"Couldn't load font %s\n",fontname);
		return 0;
	}

	font->w=w;
	font->h=h;
	font->cols=cols;
	font->rows=rows;
	font->offset=offset;
	font->spacing=w;

	GLubyte texbytes[w*h*cols*rows];
	int res=fread(texbytes,w*h*cols*rows,1,fh);
	fclose(fh);
	if(!res)
	{
		fprintf(stderr,"Couldn't read data from font file %s\n",fontname);
		return 0;
	}

	glGenTextures(1,&font->tex);
	glBindTexture(GL_TEXTURE_2D,font->tex);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
	gluBuild2DMipmaps(GL_TEXTURE_2D,GL_ALPHA,w*cols,h*rows,GL_ALPHA,GL_UNSIGNED_BYTE,texbytes);
//	gluBuild2DMipmaps(GL_TEXTURE_2D,GL_LUMINANCE,w*cols,h*rows,GL_LUMINANCE,GL_UNSIGNED_BYTE,texbytes);
//	glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,w*cols,h*rows,0,GL_LUMINANCE,GL_UNSIGNED_BYTE,texbytes);

	font->lists=glGenLists(rows*cols);
	for(int y=0;y<rows;y++)
	for(int x=0;x<cols;x++)
	{
		glNewList(font->lists+y*cols+x,GL_COMPILE);
		glBegin(GL_QUADS);
		glTexCoord2f((float)x/(float)cols,(float)y/(float)rows);
		glVertex2i(0,0);
		glTexCoord2f((float)(x+1)/(float)cols,(float)y/(float)rows);
		glVertex2i(w,0);
		glTexCoord2f((float)(x+1)/(float)cols,(float)(y+1)/(float)rows);
		glVertex2i(w,h);
		glTexCoord2f((float)x/(float)cols,(float)(y+1)/(float)rows);
		glVertex2i(0,h);
		glEnd();
		glEndList();
	}
	return 1;
}

void DrawTextWithFont(Font *font,char *text,int x,int y)
{
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D,font->tex);

	glMatrixMode(GL_MODELVIEW);

	int x_pos=x;
	for(unsigned char *ptr=(unsigned char *)text;*ptr;ptr++)
	{
		int c=*ptr;
		if(c>=font->offset&&c<font->offset+font->cols*font->rows)
		{
			glPushMatrix();
			glTranslatef(x_pos,y,0);
			glCallList(font->lists+c-font->offset);
			glPopMatrix();
		}
		x_pos+=font->spacing;
	}
}

void DrawTextWithEffect(Font *font,char *text,int x,int y,int effect,double t)
{

}
